var parseManifest = require("parse-appcache-manifest");
var request = require('request');
var config = require("./config");

var x5UIPath = config.serverPath;

//http://192.168.1.49:8080/x5/$v@build_version@_no_$lzh_CN$s/UI2/SA/appcache/apps.j
//http://192.168.1.49:8080/x5/$v@build_version@_no_$lzh_CN$s/UI2/SA/appcache/getManifest.j?requestCacheApps=demo,SA,system,portal,test
var cacheManifest = function(callback){
    var appcacheUrl = x5UIPath + "/"+config.serverName+"/"+config.modelName+"/SA/appcache/getManifest.j?requestCacheApps="+config.requestCacheApps;
    var options = {
        url: appcacheUrl,
        headers: {
            'content-type':"text/cache-manifest"
        }
    };
    request(appcacheUrl, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body) // Print the google web page.
            var entries = parseManifest(body);
            var number = entries.cache.length;
            for(var index in entries.cache){
                var requestUrl = "http://127.0.0.1:"+ config.localPort + entries.cache[index];
                request(requestUrl, function (error, response, body) {
                    if(!error && response.statusCode == 200){
                        console.log("\n缓存"+ requestUrl + "成功!");
                        number--;
                        if(number == 0){
                            callback && callback();
                        }
                    }else{
                        callback && callback(error);
                    }
                });
            }
        }else if(error){
            callback && callback(error);
        }
    });


};
module.exports = cacheManifest;

